import React, { useEffect, useState } from 'react';
import {
  Card,
  Table,
  Button,
  Space,
  Modal,
  Form,
  Input,
  Select,
  InputNumber,
  message,
  Popconfirm,
  Tag,
  Row,
  Col,
  Statistic,
  Typography,
} from 'antd';
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  EyeOutlined,
  BarChartOutlined,
} from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { useAppDispatch, useAppSelector } from '../store/hooks';
import { RootState } from '../store';
import ResizableTable from '../components/ResizableTable';
import {
  fetchPortfolios,
  createPortfolio,
  updatePortfolio,
  deletePortfolio,
} from '../store/slices/portfolioSlice';
import MainLayout from '../components/Layout/MainLayout';
import { Portfolio as PortfolioType, RISK_LEVELS } from '../types';

const { Title, Text } = Typography;
const { Option } = Select;

const Portfolio: React.FC = () => {
  const navigate = useNavigate();
  const dispatch = useAppDispatch();
  const { portfolios, loading } = useAppSelector((state: RootState) => state.portfolio);
  const [form] = Form.useForm();
  const [modalVisible, setModalVisible] = useState(false);
  const [editingPortfolio, setEditingPortfolio] = useState<PortfolioType | null>(null);

  useEffect(() => {
    dispatch(fetchPortfolios());
  }, [dispatch]);

  const handleCreate = () => {
    setEditingPortfolio(null);
    form.resetFields();
    setModalVisible(true);
  };

  const handleEdit = (portfolio: PortfolioType) => {
    setEditingPortfolio(portfolio);
    form.setFieldsValue(portfolio);
    setModalVisible(true);
  };

  const handleDelete = async (id: number) => {
    try {
      await dispatch(deletePortfolio(id)).unwrap();
      message.success('投资组合删除成功');
    } catch (error) {
      message.error('删除失败');
    }
  };

  const handleSubmit = async (values: any) => {
    try {
      // 将前端字段映射到后端期望的字段
      const submitData = {
        name: values.name,
        description: values.description,
        total_amount: values.initial_amount, // 将initial_amount映射到total_amount
      };
      
      if (editingPortfolio) {
        await dispatch(updatePortfolio({ id: editingPortfolio.id, data: submitData })).unwrap();
        message.success('投资组合更新成功');
      } else {
        await dispatch(createPortfolio(submitData)).unwrap();
        message.success('投资组合创建成功');
      }
      setModalVisible(false);
      form.resetFields();
    } catch (error: any) {
      console.error('Portfolio operation error:', error);
      message.error(editingPortfolio ? '更新失败' : '创建失败');
    }
  };

  const columns = [
    {
      title: '组合名称',
      dataIndex: 'name',
      key: 'name',
      render: (text: string, record: PortfolioType) => (
        <Button
          type="link"
          onClick={() => navigate(`/portfolio/${record.id}`)}
          style={{ padding: 0 }}
        >
          {text}
        </Button>
      ),
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
      ellipsis: true,
    },
    {
      title: '风险等级',
      dataIndex: 'risk_level',
      key: 'risk_level',
      render: (level: number) => (
        <Tag color={level <= 2 ? 'green' : level <= 3 ? 'orange' : 'red'}>
          {RISK_LEVELS[level as keyof typeof RISK_LEVELS]}
        </Tag>
      ),
    },
    {
      title: '总价值',
      dataIndex: 'total_value',
      key: 'total_value',
      render: (value: number) => `¥${value ? value.toLocaleString() : '0'}`,
      sorter: (a: PortfolioType, b: PortfolioType) => a.total_value - b.total_value,
    },
    {
      title: '总收益',
      dataIndex: 'total_return',
      key: 'total_return',
      render: (value: number) => (
        <Text type={value >= 0 ? 'success' : 'danger'}>
          {value >= 0 ? '+' : ''}¥{value ? value.toLocaleString() : '0'}
        </Text>
      ),
      sorter: (a: PortfolioType, b: PortfolioType) => a.total_return - b.total_return,
    },
    {
      title: '收益率',
      key: 'return_rate',
      render: (_: any, record: PortfolioType) => {
        const rate = record.total_value > 0 ? (record.total_return / record.total_value) * 100 : 0;
        return (
          <Text type={rate >= 0 ? 'success' : 'danger'}>
            {rate >= 0 ? '+' : ''}{rate.toFixed(2)}%
          </Text>
        );
      },
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      key: 'created_at',
      render: () => {
        return new Date().toLocaleDateString();
      },
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: PortfolioType) => (
        <Space>
          <Button
            type="link"
            icon={<EyeOutlined />}
            onClick={() => {
              if (record.id) {
                navigate(`/portfolio/${record.id}`);
              } else {
                message.error('投资组合ID无效');
              }
            }}
          >
            查看
          </Button>
          <Button
            type="link"
            icon={<BarChartOutlined />}
            onClick={() => {
              if (record.id) {
                navigate(`/portfolio/${record.id}/analysis`);
              } else {
                message.error('投资组合ID无效');
              }
            }}
          >
            分析
          </Button>
          <Button
            type="link"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Popconfirm
            title="确定要删除这个投资组合吗？"
            onConfirm={() => {
              if (record.id) {
                handleDelete(record.id);
              } else {
                message.error('投资组合ID无效');
              }
            }}
            okText="确定"
            cancelText="取消"
          >
            <Button
              type="link"
              danger
              icon={<DeleteOutlined />}
            >
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  // 计算总体统计
  const portfolioList = Array.isArray(portfolios) ? portfolios : [];
  const totalAssets = portfolioList.reduce((sum: number, portfolio: PortfolioType) => sum + portfolio.total_value, 0);
  const totalReturn = portfolioList.reduce((sum: number, portfolio: PortfolioType) => sum + portfolio.total_return, 0);
  const totalReturnRate = totalAssets > 0 ? (totalReturn / totalAssets) * 100 : 0;

  return (
    <MainLayout>
      <div>
        <div style={{ marginBottom: 24 }}>
          <Title level={2}>投资组合管理</Title>
          <Text type="secondary">管理您的投资组合，跟踪投资表现</Text>
        </div>

        {/* 统计概览 */}
        <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
          <Col xs={24} sm={8}>
            <Card>
              <Statistic
                title="组合总数"
                value={portfolioList.length}
                valueStyle={{ color: '#1890ff' }}
              />
            </Card>
          </Col>
          <Col xs={24} sm={8}>
            <Card>
              <Statistic
                title="总资产价值"
                value={totalAssets}
                precision={2}
                valueStyle={{ color: '#722ed1' }}
                prefix="¥"
              />
            </Card>
          </Col>
          <Col xs={24} sm={8}>
            <Card>
              <Statistic
                title="总收益率"
                value={totalReturnRate}
                precision={2}
                valueStyle={{ color: totalReturnRate >= 0 ? '#52c41a' : '#ff4d4f' }}
                suffix="%"
              />
            </Card>
          </Col>
        </Row>

        {/* 投资组合列表 */}
        <Card
          title="投资组合列表"
          extra={
            <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={handleCreate}
            >
              创建投资组合
            </Button>
          }
        >
          <ResizableTable
            columns={columns}
            dataSource={portfolioList}
            loading={loading}
            rowKey="id"
            pagination={{
              pageSize: 10,
              showSizeChanger: true,
              showQuickJumper: true,
              showTotal: (total) => `共 ${total} 个投资组合`,
            }}
          />
        </Card>

        {/* 创建/编辑模态框 */}
        <Modal
          title={editingPortfolio ? '编辑投资组合' : '创建投资组合'}
          open={modalVisible}
          onCancel={() => {
            setModalVisible(false);
            form.resetFields();
          }}
          footer={null}
          width={600}
        >
          <Form
            form={form}
            layout="vertical"
            onFinish={handleSubmit}
          >
            <Form.Item
              name="name"
              label="组合名称"
              rules={[
                { required: true, message: '请输入组合名称' },
                { max: 100, message: '名称不能超过100个字符' },
              ]}
            >
              <Input placeholder="请输入组合名称" />
            </Form.Item>

            <Form.Item
              name="description"
              label="组合描述"
              rules={[
                { max: 500, message: '描述不能超过500个字符' },
              ]}
            >
              <Input.TextArea
                rows={3}
                placeholder="请输入组合描述（可选）"
              />
            </Form.Item>

            <Form.Item
              name="risk_level"
              label="风险等级"
              rules={[{ required: true, message: '请选择风险等级' }]}
            >
              <Select placeholder="请选择风险等级">
                {Object.entries(RISK_LEVELS).map(([key, value]) => (
                  <Option key={key} value={parseInt(key)}>
                    {value}
                  </Option>
                ))}
              </Select>
            </Form.Item>



            <Form.Item
              name="initial_amount"
              label="初始金额"
              rules={[
                { required: true, message: '请输入初始金额' },
                { type: 'number', min: 0, message: '金额必须大于等于0' },
              ]}
            >
              <InputNumber
                style={{ width: '100%' }}
                placeholder="请输入初始金额"
                formatter={(value) => `¥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
                parser={(value) => value!.replace(/¥\s?|(,*)/g, '') as any}
                min={0}
                precision={2}
              />
            </Form.Item>

            <Form.Item style={{ marginBottom: 0, textAlign: 'right' }}>
              <Space>
                <Button
                  onClick={() => {
                    setModalVisible(false);
                    form.resetFields();
                  }}
                >
                  取消
                </Button>
                <Button type="primary" htmlType="submit">
                  {editingPortfolio ? '更新' : '创建'}
                </Button>
              </Space>
            </Form.Item>
          </Form>
        </Modal>
      </div>
    </MainLayout>
  );
};

export default Portfolio;